package com.ttmusic.view.adapters;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.SectionIndexer;
import android.widget.TextView;


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import com.ttmusic.activitys.R;
import com.ttmusic.comparator.MusicInfoComparator;
import com.ttmusic.core.MusicManager;
import com.ttmusic.entity.AbstractMusic;
import com.ttmusic.entity.MusicInfo;
import com.ttmusic.view.listeners.OnItemClickListener;


/**
 * ListView展示歌曲列表时必须的适配器
 * @author Administrator
 *
 */
public class MusicAdapter extends BaseAdapter implements SectionIndexer {


    private Context mContext;
    private List<AbstractMusic> list = new ArrayList<AbstractMusic>();
    private OnItemClickListener listener;
    private boolean isABC;
    //歌曲的排序方式 默认按歌曲名称排序
  	private static SortType sortType = SortType.SORT_BY_TITLE;
    
    public MusicAdapter(Context mContext, List<AbstractMusic> list, boolean isABC) {
        this.mContext = mContext;
        this.list = list;
        this.isABC = isABC;
        //对歌曲进行排序
        if(isABC)    Collections.sort(this.list, new MusicInfoComparator());
    }
    
    /**
     * 改变排序方式 对集合数据重新排序 并且通知ListView按新的数据重新展示
     * 		改变排序方式对当前展示的ListView进行改变展示效果
     * 		改变排序方式对当前播放的ListView的歌曲列表进行重新编号(重设当前播放编号)
     */
    public void changeSortType() {
    	//对歌曲进行排序
        if(isABC)    Collections.sort(this.list, new MusicInfoComparator());
        AbstractMusic am = MusicManager.getNowPlayingSong();
        if(am != null && this.list == MusicManager.getPlayingList()) {
        	//重新排序后 获取当前播放的歌曲在播放列表中的新索引
        	int index = this.list.indexOf(am);
        	if(index >= 0) {
        		MusicManager.setNowPlayingIndex(index);
        	}
        }
        this.notifyDataSetChanged();
    }
    
    /**
     * 改变数据了-用在扫描本地歌曲完成之后
     * @param newMusicList
     */
    public void changeData(List<AbstractMusic> newMusicList) {
//    	list.clear();
//    	list.addAll(newMusicList);
    	list = newMusicList;
    	//对歌曲进行排序
        if(isABC)    Collections.sort(this.list, new MusicInfoComparator());
        this.notifyDataSetChanged();
    }


    @SuppressWarnings("rawtypes")
	public List getList() {
        return list;
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }

	public void setListener(OnItemClickListener listener) {
		this.listener = listener;
	}

	@Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int i) {
        return list.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    /**
     * 
     * @param position 当前行号
     * @param convertView 当前行
     * @param parent 父级元素
     */
    @SuppressLint("InflateParams")
	@Override
    public View getView(final int position, View convertView, final ViewGroup parent) {
        ViewHolder mViewHolder = null;
        if (convertView == null) {
            mViewHolder = new ViewHolder();
            convertView = LayoutInflater.from(mContext).inflate(R.layout.listitem_song, null);
            mViewHolder.song_text = (TextView) convertView.findViewById(R.id.song_title);
            mViewHolder.letter_text = (TextView) convertView.findViewById(R.id.catalog);
            mViewHolder.artist_tv = (TextView) convertView.findViewById(R.id.artist_tv);
            mViewHolder.duration_tv = (TextView) convertView.findViewById(R.id.duration_tv);
            mViewHolder.selected_view = convertView.findViewById(R.id.selected_view);
            mViewHolder.song_item = (LinearLayout) convertView.findViewById(R.id.song_item);
            convertView.setTag(mViewHolder);
        } else {
            mViewHolder = (ViewHolder) convertView.getTag();
        }

        //Song song = (Song) getItem(position);
        MusicInfo musicInfo = (MusicInfo) getItem(position);

        //String title = isABC ? "" : (position+1)+".";
        mViewHolder.song_text.setText(musicInfo.getTitle());
        mViewHolder.artist_tv.setText(musicInfo.getArtist() + " - " + musicInfo.getAlbum());
        mViewHolder.duration_tv.setText(musicInfo.getDurationStr());

        if(isABC) {
            int section = getSectionForPosition(position);
            if (position == getPositionForSection(section)) {
                mViewHolder.letter_text.setVisibility(View.VISIBLE);
                String letterText = "#";
            	if(sortType == SortType.SORT_BY_ADDTIME) {
            		//添加时间还没获取到，要先做扫描，将歌曲信息保存到SQLite数据库中 增加一个添加时间字段
            	}else if(sortType == SortType.SORT_BY_ARTIST) {
            		letterText = musicInfo.getPinYinHeadCharofArtist();
            	}else if(sortType == SortType.SORT_BY_ALBUM) {
            		letterText = musicInfo.getPinYinHeadCharofAlbum();
            	}else {
            		letterText = musicInfo.getPinYinHeadCharofTitle();
            	}
                mViewHolder.letter_text.setText(letterText.charAt(0)+"");
            } else {
                mViewHolder.letter_text.setVisibility(View.GONE);
            }
        }else{
            mViewHolder.letter_text.setVisibility(View.GONE);
        }
        mViewHolder.song_item.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(listener!=null){
                    listener.onItemClick(position);
                    notifyDataSetChanged();
                }
            }
        });
        //当行号等于正在播放的歌曲编号   playing_icon展示在点击的当前行  其他行的此图标就隐藏
    	if(MusicManager.getPlayingList() == list && MusicManager.getNowPlayingIndex() == position) {
    		mViewHolder.selected_view.setVisibility(View.VISIBLE);
    	}else {
    		mViewHolder.selected_view.setVisibility(View.GONE);
    	}
        return convertView;
    }

    


    final static class ViewHolder {
        TextView song_text;
        TextView letter_text;
        TextView artist_tv;
        TextView duration_tv;
        View selected_view;
        LinearLayout song_item;
    }

    @Override
    public Object[] getSections() {
        return null;
    }

    @Override
    public int getPositionForSection(int section) {
        for (int i = 0; i < getCount(); i++) {
            String sortStr = "#";
            if(sortType == SortType.SORT_BY_ADDTIME) {
        		
        		//添加时间还没获取到，要先做扫描，将歌曲信息保存到SQLite数据库中 增加一个添加时间字段
        	}else if(sortType == SortType.SORT_BY_ARTIST) {
        		sortStr = ((MusicInfo) getItem(i)).getPinYinHeadCharofArtist();
        	}else if(sortType == SortType.SORT_BY_ALBUM) {
        		sortStr = ((MusicInfo) getItem(i)).getPinYinHeadCharofAlbum();
        	}else {
        		sortStr = ((MusicInfo) getItem(i)).getPinYinHeadCharofTitle();
        	}
            char firstchar = sortStr.charAt(0);
            if (firstchar == section) return i;
        }
        return -1;
    }

    @Override
    public int getSectionForPosition(int position) {
    	String str = "#";
    	if(sortType == SortType.SORT_BY_ADDTIME) {
    		return str.charAt(0);
    		//添加时间还没获取到，要先做扫描，将歌曲信息保存到SQLite数据库中 增加一个添加时间字段
    	}else if(sortType == SortType.SORT_BY_ARTIST) {
    		return ((MusicInfo) getItem(position)).getPinYinHeadCharofArtist().charAt(0);
    	}else if(sortType == SortType.SORT_BY_ALBUM) {
    		return ((MusicInfo) getItem(position)).getPinYinHeadCharofAlbum().charAt(0);
    	}else {
    		return ((MusicInfo) getItem(position)).getPinYinHeadCharofTitle().charAt(0);
    	}
    }
    
    /**
	 * 获取当前排序方式
	 * @return
	 */
	public static SortType getSortType() {
		return sortType;
	}
	/**
	 * 设置排序方式
	 * @param sortType
	 */
	public static void setSortType(SortType sortType) {
		if(MusicAdapter.sortType != sortType)
			MusicAdapter.sortType = sortType;
	}
	/**
	 * 列表项排序方式枚举
	 * @author Administrator
	 *
	 */
	public static enum SortType{
		SORT_BY_ADDTIME,	//按添加时间排序
		SORT_BY_TITLE,		//按歌曲名排序
		SORT_BY_ARTIST,		//按歌手名排序
		SORT_BY_ALBUM		//按专辑名排序
	}
}
